package Threadtest;

import java.util.Objects;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class test4_API {
    public static void main(String[] args) {
        task1 task1 = new task1();
        task2 task2=new task2();

//            Thread t1=new Thread(task1);
//            Thread t2=new Thread(task2);
//            t2.setDaemon(true);
//            t1.start();
//            t2.start();
        for (int i = 0; i < 2; i++) {
            Thread t1=new Thread(task1);
            Thread t2=new Thread(task1);
            t1.start();
            t2.start();
        }



    }
}

class task1 implements Runnable{
    static int trict=10;
    @Override
    public void run() {
        while (trict>0){
            System.out.println(Thread.currentThread().getName()+"正在卖票"+"当前还有"+(trict--)+"张票");
            Thread.yield();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
class task2 implements Runnable{
    static int trict=100;
    static final Object obj=new Object();
    @Override
    public void run() {
        while (true){
            //可以设置final的对象,也可以设置为当前类的反射
            synchronized (test4_API.class){
                if (trict>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName()+"当前还有"+(trict--));
                }else {
                    break;
                }
            }
        }

    }
}
class task3 implements Runnable{
    static int trict=100;
    static final Object obj=new Object();
    static Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true){
            //用lock加锁
           // synchronized (test4_API.class){
            lock.lock();
                    try {
                        if (trict>0) {
                            Thread.sleep(10);
                            System.out.println(Thread.currentThread().getName() + "当前还有" + (trict--));
                        }
                        else {
                            break;
                        }

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        lock.unlock();
                    }
                }

        }

    }
